<script setup>
import { ref, watch } from "vue";
import WaterBalanceDiagram from "./components/WaterBalanceDiagram.vue";
import WaterBalanceConfigDrawer from "./components/WaterBalanceConfigDrawer.vue";
import { useCompanyStore } from "@/stores/company";
import { useMeterStore } from "@/stores/meter";
import { handleError } from "@/utils/handleError";
import { useAreaStore } from "@/stores/area";
import { getWaterBalanceApi, getUnknownWaterApi } from "@/api/algorithm";
import { getMetersReportApi } from "@/api/meter";
import dayjs from "dayjs";

const loading = ref(false);
const companyStore = useCompanyStore();
const areaStore = useAreaStore();
const meterStore = useMeterStore();
const drawerVisible = ref(false);

let nodes = ref([]);
let waterBalanceData = ref([]);
let totalVi = ref(0);
let leakageVi = ref(0);
//合并水平衡数据
function processWaterBalanceData(data) {
  let merged_area = data.merged_area ? data.merged_area.map((item) => ({
    ...item,
    label: areaStore.getMergedAreaNameById(item.merged_area_id),
    vco: item.vco ? +item.vco : 0,
    vi: item.vi ? +item.vi : 0,
    vd: item.vd ? +item.vd : 0,
  })) : [];
  let single_area = data.single_area ? data.single_area.map((item) => {
    let areaName = areaStore.getAreaNameById(item.area_id);
    return {
      ...item,
      label: areaName,
      vco: item.vco ? +item.vco : 0,
      vi: item.vi ? +item.vi : 0,
      vd: item.vd ? +item.vd : 0,
    }
  }) : [];

  return [...merged_area, ...single_area]
}

// 获取一级表数据
async function fetchFirstLevelData(meters) {
  try {
    loading.value = true
    let res = await getMetersReportApi({
      meters: meters,
      start_time: dayjs().subtract(8, 'day').startOf('day').valueOf(),
      end_time: dayjs().startOf('day').valueOf(),
      interval: '',
    })

    const validData = res.aggregated_data.filter(item => item.Value !== null && item.Value !== undefined)
    totalVi.value = validData.length > 0
      ? Number((validData.reduce((acc, cur) => acc + (+cur.Value), 0) / validData.length).toFixed(2))
      : 0
  } catch (error) {
    console.error('获取一级表数据失败:', error)
    ElMessage.error('获取一级表数据失败')
    throw error
  } finally {
    loading.value = false
  }
}

async function getLeakageVi() {
  let res = await getUnknownWaterApi({
    id: companyStore.currentCompany.id,
    start_time: dayjs().subtract(8, 'day').startOf('day').valueOf(),
    end_time: dayjs().startOf('day').valueOf(),
  })
  console.log(res);
  leakageVi.value = res.data.unknown_water
}


async function loadData() {
  try {
    loading.value = true;
    await areaStore.fetchMergedAreaList({
      company_id: companyStore.currentCompany.id
    })
    await meterStore.fetchMeterList({
      company_id: companyStore.currentCompany.id,
      type: 1
    })
    await getLeakageVi()
    let res = await getWaterBalanceApi({
      id: companyStore.currentCompany.id,
      start_time: dayjs().subtract(8, 'day').startOf('day').valueOf(),
      end_time: dayjs().startOf('day').valueOf(),
    })
    nodes.value = res.data;
    await fetchFirstLevelData(meterStore.meterLevels[0])
    let processedNodes = processWaterBalanceData(res.data);
    waterBalanceData.value = processedNodes;
  } catch (error) {
    handleError(error, "获取水平衡数据失败");
  } finally {
    loading.value = false;
  }
}

// 监听公司变化
watch(
  () => companyStore.currentCompany,
  loadData,
  {
    immediate: true,
  }
);

// 处理配置保存
const handleConfigSave = (updatedNodes) => {
  try {
    // 验证所有节点的比例之和是否为10
    const isValid = updatedNodes.every(
      (node) => Math.abs(node.consumptionRatio + node.drainageRatio - 10) < 0.1
    );

    if (!isValid) {
      ElMessage.error("存在比例配置错误，请检查");
      return;
    }

    // 更新节点数据
    waterBalanceStore.nodes = updatedNodes;
    ElMessage.success("配置已保存");
    drawerVisible.value = false;
  } catch (error) {
    handleError(error, "配置保存失败");
  }
};


</script>

<template>
  <div class="water-balance-page">
    <el-card class="main-card" v-loading.value="loading" body-style="flex:1">
      <template #header>
        <span>水平衡图</span>
        <div class="header-controls">
          <el-button type="primary" @click="drawerVisible = true">
            配置
          </el-button>
        </div>
      </template>

      <div v-if="!loading" class="diagram-container">
        <water-balance-diagram :nodes="waterBalanceData" :water-source-vi="totalVi" :leakage-vi="leakageVi" />
      </div>
    </el-card>

    <water-balance-config-drawer @refresh="loadData" v-model:visible="drawerVisible" :nodes="nodes"
      @save="handleConfigSave" />
  </div>
</template>

<style scoped>
.water-balance-page {
  height: 100%;
  width: 100%;
  background-color: #f5f7fa;
  padding: 20px;
}

.main-card {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.diagram-container {
  height: 100%;
  width: 100%;
  padding: 20px;
  background-color: #fff;
}
</style>
